package com.controller;

import com.config.Result;
import com.dao.BuildingDao;
import com.pojo.Building;
import com.pojo.StudentInfo;
import com.service.impl.BuildServiceImpl;
import com.service.impl.DormitoryServiceImpl;
import com.service.impl.StudentInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentInfoServiceImpl studentInfoService;

    @Autowired
    BuildServiceImpl buildService;

    @Autowired
    DormitoryServiceImpl dormitoryService;

    @Autowired
    BuildingDao buildingDao;


    /**
     * 带参数查询
     *
     * @param param
     * @return
     */
    @GetMapping("/search")
    public Result<?> FindStuByParam(@RequestParam String param) {
        List<StudentInfo> studentInfos = studentInfoService.searchByParam(param);
        if (studentInfos == null){
            return Result.error("-1","查询失败");
        }
        return Result.success(studentInfos);
    }

    @PostMapping("/deleteById/{sno}")
    public Result<?> deleteById(@PathVariable String sno){

        if (sno == null){
            return Result.error("-1","学号为空");
        }
        Integer integer = studentInfoService.deleteById(sno);
        if (integer != 1){
            return Result.error("-1","删除失败");
        }
        return Result.success();
    }


    @PostMapping("/updateById/{sno}")
    public Result<?> updateById(@PathVariable String sno,@RequestBody StudentInfo studentInfo){

        String dormitory = studentInfo.getDormitory()+"";

        String buildName = dormitoryService.selectBuildByName(dormitory);

        if (buildName == null){
            return Result.error("-1","不存在该宿舍");
        }

        Building building = buildingDao.selectByName(buildName);

        if (sno == null){
            return Result.error("-1","学号为空");
        }
        if (studentInfo == null){
            return Result.error("-1","数据为空");
        }

        studentInfo.setSno(sno);

        Integer integer = studentInfoService.updateById(studentInfo,Integer.parseInt(building.getId()));
        if (integer != 1){
            return Result.error("-1","更新失败");
        }
        return Result.success();
    }



}
